package com.tajiang.business.mess.adapter;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tajiang.business.R;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.http.BaseResponse;
import com.tajiang.business.common.http.HttpHandler;
import com.tajiang.business.common.http.HttpResponseListener;
import com.tajiang.business.common.utils.GlideRoundTransform;
import com.tajiang.business.common.utils.ImageUtils;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.widget.LoadingDialog;
import com.tajiang.business.common.widget.dialog.CDialog;
import com.tajiang.business.model.FoodManageMent;

import java.math.BigDecimal;
import java.net.URI;
import java.text.NumberFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Admins on 2016/10/10.
 */

public class FoodMangementAdapter extends RecyclerView.Adapter<FoodMangementAdapter.MyViewHolder> {

    private Context mContext;
    private List<FoodManageMent> mDdataList;
    private OnFoodItemMangementListener mItemtListener;
    private NumberFormat numberFormat = NumberFormat.getInstance();

    private LoadingDialog loadingDialog;
    private CDialog foodDetail;
    private Uri imageUri;

    /**
     * 菜品的上传和下架 接口
     *
     * @param listener
     */
    public void setOnFoodItemMangementListener(OnFoodItemMangementListener listener) {
        this.mItemtListener = listener;
    }

    public interface OnFoodItemMangementListener {
        public void OnFoodItemChangeState(List<FoodManageMent> dataList, int position);
    }

    public FoodMangementAdapter(Context context, List<FoodManageMent> dataList) {
        this.mContext = context;
        this.mDdataList = dataList;
        this.loadingDialog = new LoadingDialog(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_food_menu_mangement, null);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        FoodManageMent item = mDdataList.get(position);
        initItemView(holder, item);
        holder.tvFoodName.setText(item.getName());
        holder.tvFoodPrice.setText("￥" + String.valueOf(item.getMarketprice().setScale(2, BigDecimal.ROUND_DOWN).toString()));
//        LogUtils.e("name = " + item.getName() + ",id = " + item.getId() + ", url = " + item.getImage());
        Glide.with(mContext)
                .load(item.getImage())
                .transform(new CenterCrop(mContext)   //此方式解决CenterCrop与Transformer的共存问题
                        ,new GlideRoundTransform(mContext, 4))
                .placeholder(R.mipmap.icon_empty_good)
                .error(R.mipmap.icon_empty_good)
                .crossFade()
                .into(holder.ivPicFoodSelect);
    }

    private void initItemView(MyViewHolder holder, FoodManageMent item) {
        switch (item.getState()) {
            case FoodManageMent.FOOD_ON_SALE:
                holder.btnFoodShelfManagement.setBackgroundResource(R.drawable.shape_line_round_dark_corner_4);
                holder.btnFoodShelfManagement.setTextColor(mContext.getResources().getColor(R.color.text_black_dark));
                holder.btnFoodShelfManagement.setText("下架");
                holder.llTransparentLayout.setVisibility(View.GONE);
                break;
            case FoodManageMent.FOOD_OFF_SALE:
                holder.btnFoodShelfManagement.setBackgroundResource(R.drawable.shape_line_round_green_corner_4);
                holder.btnFoodShelfManagement.setTextColor(mContext.getResources().getColor(R.color.green));
                holder.btnFoodShelfManagement.setText("上架");
                holder.llTransparentLayout.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public int getItemCount() {
        return mDdataList.size();
    }

    public void updateAllDataSet(List<FoodManageMent> dataList) {
        this.mDdataList.clear();
        this.mDdataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public void addAllAndUpdateDataSet(List<FoodManageMent> dataList) {
        this.mDdataList.addAll(dataList);
        notifyDataSetChanged();
    }

    public List<FoodManageMent> getData() {
        return mDdataList;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_pic_food_select)
        ImageView ivPicFoodSelect;
        @BindView(R.id.tv_food_name)
        TextView tvFoodName;
        @BindView(R.id.tv_food_price)
        TextView tvFoodPrice;
        @BindView(R.id.tv_food_shelf_management)
        Button btnFoodShelfManagement;
        @BindView(R.id.ll_transparent_layout)
        LinearLayout llTransparentLayout;

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            initLister();
        }

        private void initLister() {
            //菜品的上下架
            btnFoodShelfManagement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mDdataList.get(getLayoutPosition()).getState() == FoodManageMent.FOOD_ON_SALE
                            || mDdataList.get(getLayoutPosition()).getStorage() > 0) {
                        //TODO......执行上下架网络请求.......
                        doUpdateFoodRequest(mDdataList.get(getLayoutPosition()));
                        if (mItemtListener != null) {
                            mItemtListener.OnFoodItemChangeState(mDdataList, getLayoutPosition());
                        }
                    } else {
                        ToastUtils.showShort(" 库存为0，不能上架");
                    }
                }
            });
            //点击查看大图
//            ivPicFoodSelect.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    showGoodDetailDialog(mDdataList.get(getLayoutPosition()));
//                }
//            });
        }

        private void showGoodDetailDialog(final FoodManageMent goods) {
            if (foodDetail == null) {
                foodDetail = new CDialog(mContext, R.layout.dialog_food_detail);
            }
            View contentView = foodDetail.getContentView();
            TextView tv_nameFoodDetailDialog = (TextView) contentView.findViewById(R.id.tv_nameFoodDetailDialog);
            TextView tv_priceFoodDetailDialog = (TextView) contentView.findViewById(R.id.tv_priceFoodDetailDialog);

            // 加载套餐大图
            SimpleDraweeView simpleDraweeView =  foodDetail.findChildViewById(R.id.iv_picGoodDetial);
            ImageUtils.loadImage(getContext() , simpleDraweeView, goods.getImage(), null);

            tv_nameFoodDetailDialog.setText(goods.getName());
            tv_priceFoodDetailDialog.setText(goods.getPrice() + "");

            foodDetail.show();
        }

        /**
         * 执行上下架网络请求
         *
         * @param item
         */
        private void doUpdateFoodRequest(final FoodManageMent item) {
            loadingDialog.show();
            new HttpHandler(new HttpResponseListener() {
                @Override
                public void onSuccess(BaseResponse response) {
                    if ((Boolean) response.getData() == true) {
                        ToastUtils.showShort(item.getState() == FoodManageMent.FOOD_ON_SALE
                                ?"已停售" :"已开售");
                        updateItemView(item);
                    } else {
                        ToastUtils.showShort(item.getState() == FoodManageMent.FOOD_ON_SALE
                                ?"下架失败" :"上架失败");
                    }
                }

                @Override
                public void onFailed(BaseResponse response) {

                }

                @Override
                public void onFinish() {
                    if (loadingDialog.isShowing()) {
                        loadingDialog.dismiss();
                    }
                }
            }).updateGoodsState(item.getId(), item.getState() == FoodManageMent.FOOD_ON_SALE
                    ? FoodManageMent.FOOD_OFF_SALE
                    : FoodManageMent.FOOD_ON_SALE);
        }

        /**
         * 更新本地Item View
         * @param item
         */
        private void updateItemView(FoodManageMent item) {
            switch (item.getState()) {
                case FoodManageMent.FOOD_ON_SALE:
                    btnFoodShelfManagement.setBackgroundResource(R.drawable.shape_line_round_green_corner_4);
                    btnFoodShelfManagement.setTextColor(mContext.getResources().getColor(R.color.green));
                    btnFoodShelfManagement.setText("上架");
                    llTransparentLayout.setVisibility(View.VISIBLE);
                    item.setState(FoodManageMent.FOOD_OFF_SALE);
                    break;
                case FoodManageMent.FOOD_OFF_SALE:
                    btnFoodShelfManagement.setBackgroundResource(R.drawable.shape_line_round_dark_corner_4);
                    btnFoodShelfManagement.setTextColor(mContext.getResources().getColor(R.color.text_black_dark));
                    btnFoodShelfManagement.setText("下架");
                    llTransparentLayout.setVisibility(View.GONE);
                    item.setState(FoodManageMent.FOOD_ON_SALE);
                    break;
            }
        }

        public Context getContext() {
            return itemView.getContext();
        }

    }
}

